import { customRef, reactive, ref } from "vue";
import { request } from "../../../utils/request";
import { getCourse } from "./../../../api/modules/course";
import { ElMessage, type FormInstance } from "element-plus";

interface File {
  correlationId: string;
  createdTime: string;
  fileUrl: string;
  id: string;
  name: string;
  type: string;
}

interface Course {
  createdBy: string;
  createdByName: string;
  createdTime: string;
  files: File[];
  id: string;
  name: string;
  updatedTime: string;
}

export function useCourse() {
  const courseList = ref<Course[]>([]);

  // 课程管理相关
  const courseDialogVisible = ref(false);
  const currentCourse = ref<any>();
  const courseForm = reactive<{ title: string; file?: File }>({
    title: "",
  });
  const courseFormRef = ref<FormInstance>();

  function getCourseList(id?: string) {
    request({
      fn: getCourse,
      params: [id],
      success(res) {
        console.log(res);
        courseList.value = res.data;
      },
    });
  }

  function saveCourse() {
    courseFormRef.value?.validate((valid) => {
      if (!valid) return;
      ElMessage.success("课程添加成功");
      courseDialogVisible.value = false;
    });
  }

  function handleMaterialUpload() {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "video/*";
    input.onchange = () => {
      const file = input.files?.[0] as unknown as File;
      if (/.(mp4|avi|mov|wmv|flv|mpeg|mpg|m4v|webm)$/.test(file.name)) {
        ElMessage.error("请上传视频文件");
        return;
      }
      courseForm.file = file;
    };
    input.click();
  }

  function deleteMaterial() {
    courseForm.file = undefined;
  }

  return {
    courseList,
    courseDialogVisible,
    currentCourse,
    courseForm,
    courseFormRef,

    getCourseList,
    saveCourse,
    handleMaterialUpload,
    deleteMaterial,
  };
}
